const config = require("./config.js");
const appkey = config.APPKEY;
const Storage = require("./storage.js");
const util = require("./utils.js");
const toast = require("./toasts.js");
const wechat = require("./wechat.js");

export function request(path, data, srcResolve, srcReject) {

  var app = getApp();

  var srcPath = path;
  var srcData = data;


  if (app) {
    var globalData = app.globalData;

    if (data) {
      if (globalData.sourceType) {
        data.sourceType = globalData.sourceType;
      }
      if (globalData.sourceId) {
        data.sourceId = globalData.sourceId;
      }
    }
  }

  let url = config.HOSTNAME + path;
  let nonceStr = util.generate_random(16);
  let sign = util.generate_sign(nonceStr, data);
  let header = {
    appkey: appkey,
    sign: sign
  };
  let form = Object.assign({
    nonceStr
  }, data);
  var now = this;
  return new Promise((resolve, reject) => {
    Storage.get("auth").then(auth => {
      // console.log(auth);
      wx.request({
        url: url,
        data: form,
        method: "post",
        header: {
          "Content-Type": "application/x-www-form-urlencoded",
          appkey: appkey,
          sign: sign,
          token: auth ? auth.token : "",
          uid: auth ? auth.uid + "" : ""
        },
        success: (res) => {
          if (!res.data.success) {
            if (app) {
              app.aldstat.sendEvent('request_fail', {
                'api': path,
                'errorMsg': res.data.errorMsg,
                'errorCode': res.data.code,
              });
            }
          }

          // 重新登录
          if (res.data.code == '20004') {
            // util.clearUserCache();
            wechat.getOpenId().then(data => {
              var openid = data.openid;
              var unionid = data.unionid ? data.unionid : openid;
              user_weixinLogin({
                openId: config.tryopenid ? config.tryopenid : openid,
                unionId: config.tryopenid ? config.tryopenid : unionid
              }).then(res => {
                if (res.code == "0") {
                  // console.log(res);
                  let token = res.result.token;
                  let uid = res.result.user.id;
                  let user = res.result.user;
                  Storage.set("auth", {
                    token: token,
                    uid: uid
                  }, 24 * 60 * 60 * 10);
                  Storage.set("current_user", user, 24 * 60 * 60 * 10);

                  request(srcPath, srcData, resolve, reject);
                }
              })
            });
            return;
          }
          if (srcResolve) {
            srcResolve(res.data);
          } else {
            resolve(res.data);
          }
          if (path != '/op/formId') {
            toast.hideLoading();
          }
        },
        fail: (err) => {
          if (app) {
            app.aldstat.sendEvent('request_fail', {
              'api': path,
              'errorMsg': err.errMsg,
            });
          }

          if (srcReject) {
            srcReject(err);
          } else {
            reject(err);
          }
          if (path != '/op/formId') {
            toast.hideLoading();
          }
        }
      })
    });
  });


};


/*-------获取短信验证码-------*/
export const card_getCode = (data = {}) => {
  return request("/card/getCode", data);
};
export const card_scan = (data = {}) => {
  return request("/card/scan", data);
};

export const card_add_self = (data = {}) => {
  return request("/card/addHolderSelf", data);
};

export const card_del_self = (data = {}) => {
  return request("/card/delHolderSelf", data);
};

export const card_edit_self = (data = {}) => {
  return request("/card/editHolderSelf", data);
};


/*-------创建名片------------*/
export const card_create = (data = {}) => {
  return request("/card/create", data);
};

/*-------微信登录---------*/
export const user_weixinLogin = (data = {}) => {
  return request("/user/weixinLogin", data);
};

/*-------获取code---------*/
export const user_xcxJsCode = (data = {}) => {
  return request("/user/xcxJsCode", data);
};

export const address_add = (data = {}) => {
  return request("/user/addAddress", data);
};

export const address_edit = (data = {}) => {
  return request("/user/editAddress", data);
};

export const address_del = (data = {}) => {
  return request("/user/delAddress", data);
};

export const address_list = (data = {}) => {
  return request("/user/addressList", data);
};

export const address_default = (data = {}) => {
  return request("/user/defaultAddress", data);
};

export const card_bindPhone = (data = {}) => {
  return request("/card/bindPhone", data);
};

export const bind_wx_phone = (data = {}) => {
  return request("/user/bindWxPhone", data);
};

export const loc_to_address = (data = {}) => {
  return request("/location/locToAddress", data);
};

/*-------获取我收藏的名片---------*/
export const card_myFavList = (data = {}) => {
  return request("/card/myFavList", data);
};

/*-------获取我看过的名片---------*/
export const card_myViewList = (data = {}) => {
  return request("/card/myViewList", data);
};

export const card_recoList = (data = {}) => {
  return request("/card/recoList", data);
};

export const card_shareimg = (data = {}) => {
  return request("/card/shareImg", data);
};

export const card_sharecomimg = (data = {}) => {
  return request("/card/shareComImg", data);
};

export const card_shareshopimg = (data = {}) => {
  return request("/card/shareShopImg", data);
};

export const card_shareproimg = (data = {}) => {
  return request("/card/shareProImg", data);
};

export const card_shareproptimg = (data = {}) => {
  return request("/card/shareProPtImg", data);
};

export const card_shareprocutimg = (data = {}) => {
  return request("/card/shareProCutImg", data);
};

export const card_shareprimg = (data = {}) => {
  return request("/card/sharePrImg", data);
};

export const card_sharecoopimg= (data = {}) => {
  return request("/card/shareCoopImg", data);
};

export const card_shareagentimg = (data = {}) => {
  return request("/card/shareAgentImg", data);
};

export const card_sharewxgzhimg = (data = {}) => {
  return request("/card/shareWxgzhImg", data);
};

export const card_apply = (data = {}) => {
  return request("/card/apply", data);
};
// 交换名片
export const card_exchange = (data = {}) => {
  return request("/card/exchange", data);
};

export const card_my = (data = {}) => {
  return request("/card/myCard", data);
};

export const card_buytry = (data = {}) => {
  return request("/card/buyTry", data);
};

export const card_openvip = (data = {}) => {
  return request("/card/openVip", data);
};

export const card_openviporder = (data = {}) => {
  return request("/card/openVipOrder", data);
};

export const card_renewvip = (data = {}) => {
  return request("/card/renewVip", data);
};

export const card_opentry = (data = {}) => {
  return request("/card/openTry", data);
};

export const wxgzh_query = (data = {}) => {
  return request("/wxgzh/query", data);
};

export const wxgzh_change = (data = {}) => {
  return request("/wxgzh/changeStatus", data);
};
/*-------推荐记录---------*/
export const recoer_queryRecord = (data = {}) => {
  return request("/recoer/queryRecord", data);
};

export const recoer_query = (data = {}) => {
  return request("/recoer/query", data);
};

export const recoer_set = (data = {}) => {
  return request("/recoer/set", data);
};

/*-------推客信息-------*/
export const recoer_info = (data = {}) => {
  return request("/recoer/info", data);
};

/*-------访问统计-------*/
export const cus_viewStatistics = () => {
  return request("/cus/viewStatistics", {});
};

/*-------访问记录------*/
export const cus_viewRecord = (data = {}) => {
  return request("/cus/viewRecord", data);
};

/*-------获取积分账户-------*/
export const score_account = () => {
  return request("/score/account", {});
};

/*-------获取积分明细------*/
export const score_query = (data = {}) => {
  return request("/score/query", data);
};

/*-------获取账户-------*/
export const account_account = () => {
  return request("/account/account", {});
};

/*-------获取账户明细------*/
export const account_query = (data = {}) => {
  return request("/account/query", data);
};

/*-------获取红包账户------*/
export const red_account = (data = {}) => {
  return request("/red/account", data);
};

export const red_get_cash = (data = {}) => {
  return request("/red/getCash", data);
};

export const get_cash = (data = {}) => {
  return request("/account/getCash", data);
};

/*-------获取红包明细-------*/
export const red_query = (data = {}) => {
  return request("/red/query", data);
};

// 查询预约
export const cus_queryReserve = (data = {}) => {
  return request("/cus/queryReserve", data);
};
// 取消预约
export const cus_cancelReserve = (data = {}) => {
  return request("/cus/cancelReserve", data);
};
// 预约成交
export const cus_dealReserve = (data = {}) => {
  return request("/cus/dealReserve", data);
};
// 预约未成交
export const cus_undealReserve = (data = {}) => {
  return request("/cus/undealReserve", data);
};

export const reserve_change_status = (data = {}) => {
  return request("/cus/changeReserveStatus", data);
};

export const card_fav = (data = {}) => {
  return request("/card/fav", data);
};

export const card_rmfav = (data = {}) => {
  return request("/card/rmFav", data);
};

export const msg_typecount = (data = {}) => {
  return request("/msg/typeCount", data);
};

export const msg_unreadcount = (data = {}) => {
  return request("/msg/unreadCount", data);
};

export const msg_read = (data = {}) => {
  return request("/msg/read", data);
};

export const card_praise = (data = {}) => {
  return request("/card/praise", data);
};

export const seller_fav = (data = {}) => {
  return request("/seller/fav", data);
};

export const seller_my = (data = {}) => {
  return request("/seller/my", data);
};

export const seller_getbyid = (data = {}) => {
  return request("/seller/getById", data);
};

export const banner_getall = (data = {}) => {
  return request("/banner/getAll", data);
};

export const seller_rmfav = (data = {}) => {
  return request("/seller/rmFav", data);
};

export const seller_praise = (data = {}) => {
  return request("/seller/praise", data);
};

export const seller_sales = (data = {}) => {
  return request("/seller/getSales", data);
};

export const seller_departments = (data = {}) => {
  return request("/seller/queryDepartments", data);
};

export const department_add = (data = {}) => {
  return request("/seller/addDepartment", data);
};

export const department_edit = (data = {}) => {
  return request("/seller/editDepartment", data);
};

export const sales_detail = (data = {}) => {
  return request("/sales/detail", data);
};

export const sales_add = (data = {}) => {
  return request("/sales/add", data);
};

export const sales_edit = (data = {}) => {
  return request("/sales/edit", data);
};

export const shop_detail = (data = {}) => {
  return request("/shop/getById", data);
};

export const shop_query = (data = {}) => {
  return request("/shop/query", data);
};

export const shop_add = (data = {}) => {
  return request("/shop/add", data);
};

export const shop_edit = (data = {}) => {
  return request("/shop/edit", data);
};

export const card_lm = (data = {}) => {
  return request("/card/leaveMsg", data);
};

export const card_reserve = (data = {}) => {
  return request("/card/reserve", data);
};

export const card_cancel_reserve = (data = {}) => {
  return request("/card/cancelReserve", data);
};

export const card_verify = (data = {}) => {
  return request("/card/verifyRequest", data);
};

export const card_get_email_code = (data = {}) => {
  return request("/card/getEmailCode", data);
};


export const agent_detail = (data = {}) => {
  return request("/agent/detail", data);
};

export const agent_set = (data = {}) => {
  return request("/agent/setAgent", data);
};

export const agent_cominfo = (data = {}) => {
  return request("/agent/comInfo", data);
};

export const agent_add = (data = {}) => {
  return request("/agent/add", data);
};

export const agent_verify = (data = {}) => {
  return request("/agent/verify", data);
};

export const agent_mylevels = (data = {}) => {
  return request("/agent/myLevels", data);
};

export const agent_levels = (data = {}) => {
  return request("/agent/getLevels", data);
};

export const agent_editlevels = (data = {}) => {
  return request("/agent/editLevels", data);
};

export const agent_allagent = (data = {}) => {
  return request("/agent/myAllAgent", data);
};

// 保存信息
export const saveInfo = (data = {}) => {
  return request("/user/saveInfo", data);
};

// 保存信息
export const myInfo = (data = {}) => {
  return request("/user/info", data);
};


// 名片详情
export const card_detail = (data = {}) => {
  return request("/card/detail", data);
};

// 通用请求
export const req = (apiName, data = {}) => {
  return request(apiName, data);
};

export const card_edit = (data = {}) => {
  return request("/card/edit", data);
};

export const card_update_share_img = (data = {}) => {
  return request("/card/updateShareImg", data);
};

export const upload_api = () => {
  return config.HOSTNAME + '/upload/uploadFile'
};

export const scan_api = () => {
  return config.HOSTNAME + '/card/scan'
};

export const cus_statistics = (data = {}) => {
  return request("/cus/statistics", data);
};


export const cus_query = (data = {}) => {
  return request("/cus/query", data);
};

export const cus_detail = (data = {}) => {
  return request("/cus/detail", data);
};

export const cus_set_predealtime = (data = {}) => {
  return request("/cus/setPreDealTime", data);
};

export const cus_set_predealrate = (data = {}) => {
  return request("/cus/setPreDealRate", data);
};

export const cus_ai = (data = {}) => {
  return request("/cus/cusAi", data);
};
export const cus_tags = (data = {}) => {
  return request("/cus/tags", data);
};
export const cus_add_tag = (data = {}) => {
  return request("/cus/addTag", data);
};
export const cus_add_tag_to_cus = (data = {}) => {
  return request("/cus/addTagsToCus", data);
};
export const cus_set_valid = (data = {}) => {
  return request("/cus/setValid", data);
};

export const cus_change_status = (data = {}) => {
  return request("/cus/changeStatus", data);
};
export const cus_set_deal = (data = {}) => {
  return request("/cus/setDeal", data);
};

export const cus_del = (data = {}) => {
  return request("/cus/del", data);
};

export const cus_fu = (data = {}) => {
  return request("/cus/followUp", data);
};

export const op_log = (data = {}) => {
  return request("/op/log", data);
};

export const op_formid = (data = {}) => {
  return request("/op/formId", data);
};

export const op_logcom = (data = {}) => {
  return request("/op/logCom", data);
};
export const op_logworks = (data = {}) => {
  return request("/op/logWorks", data);
};

export const op_logcoupon = (data = {}) => {
  return request("/op/logCoupon", data);
};

export const op_logproduct = (data = {}) => {
  return request("/op/logProduct", data);
};

export const op_logtimeline = (data = {}) => {
  return request("/op/logTimeLine", data);
};

export const product_query = (data = {}) => {
  return request("/product/query", data);
};

export const product_detail = (data = {}) => {
  return request("/product/detail", data);
};

export const product_add = (data = {}) => {
  return request("/product/add", data);
};

export const product_edit = (data = {}) => {
  return request("/product/edit", data);
};

export const product_del = (data = {}) => {
  return request("/product/del", data);
};


export const video_add = (data = {}) => {
  return request("/video/add", data);
};

export const video_del = (data = {}) => {
  return request("/video/del", data);
};

export const video_query = (data = {}) => {
  return request("/video/query", data);
};


export const works_add = (data = {}) => {
  return request("/works/add", data);
};

export const works_del = (data = {}) => {
  return request("/works/del", data);
};

export const works_query = (data = {}) => {
  return request("/works/query", data);
};

export const coupon_query = (data = {}) => {
  return request("/coupon/query", data);
};

export const coupon_add = (data = {}) => {
  return request("/coupon/add", data);
};

export const coupon_del = (data = {}) => {
  return request("/coupon/del", data);
};

export const coupon_detail = (data = {}) => {
  return request("/coupon/detail", data);
};

export const coupon_receive = (data = {}) => {
  return request("/coupon/receiveCoupon", data);
};

export const timeline_query = (data = {}) => {
  return request("/timeLine/query", data);
};

export const timeline_add = (data = {}) => {
  return request("/timeLine/add", data);
};


export const timeline_edit = (data = {}) => {
  return request("/timeLine/edit", data);
};

export const timeline_del = (data = {}) => {
  return request("/timeLine/del", data);
};

export const timeline_detail = (data = {}) => {
  return request("/timeLine/detail", data);
};

export const cus_query_lm = (data = {}) => {
  return request("/cus/queryMsg", data);
};

export const cus_reply = (data = {}) => {
  return request("/cus/replyMsg", data);
};

export const seller_detail = (data = {}) => {
  return request("/seller/detail", data);
};

export const article_detail = (data = {}) => {
  return request("/article/detail", data);
};

export const test_pay = (data = {}) => {
  return request("/order/tetPay", data);
};

export const test_refund = (data = {}) => {
  return request("/order/refund", data);
};

export const order_create = (data = {}) => {
  return request("/order/create", data);
};

export const order_detail = (data = {}) => {
  return request("/order/detail", data);
};

export const order_pay = (data = {}) => {
  return request("/order/pay", data);
};

export const order_confirm = (data = {}) => {
  return request("/order/confirm", data);
};

export const order_send = (data = {}) => {
  return request("/order/send", data);
};

export const cart_get = (data = {}) => {
  return request("/cart/get", data);
};


export const cut_add = (data = {}) => {
  return request("/bargain/add", data);
};

export const cut_detail = (data = {}) => {
  return request("/bargain/detail", data);
};

export const cut_items = (data = {}) => {
  return request("/bargain/items", data);
};

export const cut_cut = (data = {}) => {
  return request("/bargain/cut", data);
};

export const act_query = (data = {}) => {
  return request("/activity/query", data);
};

export const act_actdetail = (data = {}) => {
  return request("/activity/actdetail", data);
};

export const act_detail = (data = {}) => {
  return request("/activity/detail", data);
};

export const act_del = (data = {}) => {
  return request("/activity/del", data);
};

export const act_add = (data = {}) => {
  return request("/activity/add", data);
};

export const upload_image = (type, success, fail) => {
  wx.chooseImage({
    count: 1,
    success: function(res) {
      var tempFilePaths = res.tempFilePaths
      upload_image_only(tempFilePaths[0],type, 0, success, fail);
    },
    fail: function (res) {
      if(fail) {
        fail();
      }
    }
  });
};

export const upload_video = (type, success, fail) => {
  wx.chooseVideo({
    sourceType: ['album', 'camera'],
    maxDuration: 15,
    camera: 'back',
    success(res) {
      console.log(res.tempFilePath)
      upload_image_only(res.tempFilePath, type,1, success, fail);
    },
    fail:function(res) {
      console.log(res);
    }
  });
};

export const upload_image_only = (path, type,isVideo, success, fail) => {
  let nonceStr = util.generate_random(16);
  let sign = util.generate_sign(nonceStr, {
    type: type,
    isVideo: isVideo ? 1 : 0,
  });
  Storage.get("auth").then(auth => {

    let header = {
      appkey: appkey,
      sign: sign,
      token: auth ? auth.token : "",
      uid: auth ? auth.uid + "" : ""
    };

    toast.showLoading();
    wx.uploadFile({
      url: (type == 'SCAN_CARD') ? scan_api():upload_api(),
      filePath: path,
      name: 'file',
      header: header,
      formData: {
        'type': type,
        isVideo: isVideo?1:0,
        'nonceStr': nonceStr
      },
      success: function(res) {
        var data = JSON.parse(res.data);
        toast.hideLoading();
        if (data.success) {
          if (success) {
            if ((type == 'SCAN_CARD')) {
              success(data.result);
            } else {
              success(data.result.url);
            }
          }
        } else {
          if (fail) {
            fail();
          } else {
            toast.show('上传失败请稍后重试');
          }
        }
      }
    })
  });
};